package br.empresa.sistema.service.impl;

import java.lang.reflect.ParameterizedType;
import java.util.Collections;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.xaloon.wicket.component.BaseFacade;

import br.empresa.sistema.dominio.Entidade;
import br.empresa.sistema.service.EntidadeServicoBase;

@Transactional
public class EntidadeServicoBaseImpl<T extends Entidade<ID>, ID> implements EntidadeServicoBase<T, ID> {

	private static final long serialVersionUID = -2775549908571784303L;

	@Autowired
	private BaseFacade baseFacade;
	
	protected Class<T> persistentClass;
	
	@SuppressWarnings("unchecked")
	public EntidadeServicoBaseImpl() {
		this.persistentClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
	}
	
	public void save(T modelObject) {
		if (modelObject.getId() == null) {
			baseFacade.save(modelObject);
		}else{
			baseFacade.merge(modelObject);
		}
		
	}

	public void delete(T o) {
		baseFacade.delete(o);
	}

	public List<T> retrieveAll() {
		return baseFacade.executeQuery("select c from " + persistentClass.getName() + " c", null);
	}

	public List<T> retrieveAll(int first, int count) {
		return baseFacade.executeQuery("select c from " + persistentClass.getName() + " c", null, true, first, count);
	}

	@SuppressWarnings("unchecked")
	public T findById(ID id) {
		return (T)baseFacade.executeQuerySingle("select c from " + persistentClass.getName() + " c where c.id=:id", Collections.singletonMap("id", id));
	}

}